<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="方案编号" prop="planId">
        <el-input
          style="width: 100px"
          v-model="queryParams.planId"
          placeholder="请输入方案编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="交易对" prop="instId">
        <el-input
          v-model="queryParams.instId"
          placeholder="请输入交易对"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="数据维度" prop="bar">
        <el-input
          v-model="queryParams.bar"
          placeholder="请输入数据维度"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="观测时间">
        <el-date-picker
          v-model="daterangeGcTime"
          style="width: 240px"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="handleDateRangeChange"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 统计信息显示区域 -->
    <div class="statistics-panel" v-if="totalData">
      <div class="stat-item"><label>当前方案: {{totalData.now || '--'}}</label></div>
      <div class="stat-item"><label>最优方案: {{totalData.max || '--'}}</label></div>
      <div class="stat-item"><label>收益排序: {{totalData.sort || '--'}}</label></div>
    </div>

    <el-table v-loading="loading" :data="detailsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- 方案信息合并列 -->
      <el-table-column label="方案信息" align="center" width="250">
        <template slot-scope="scope">
          <div style="text-align: left; line-height: 1.5;">
            <div><span style="color: red;">方案{{ scope.row.planId }}</span>:{{ scope.row.planSimple }} </div>
            <div >币种:{{ formatInstId(scope.row.instId) }} 维度: {{ scope.row.bar }}</div>
          </div>
        </template>
      </el-table-column>

      <!-- 价格信息合并列 -->
      <el-table-column label="价格信息" align="center">
        <template slot-scope="scope">
          <div style="text-align: center;">
            <div style="text-align: left; display: inline-block; line-height: 1.5;">
              <div>开盘:{{ scope.row.kpj }} | 委托:{{ scope.row.wtj }}</div>
              <div>止盈:{{ scope.row.zyj }} | 止损:{{ scope.row.zsj }}</div>
              <div>平仓:{{ scope.row.mcj }} |
                <span :style="{ color: getSylColor(scope.row.syl) }"> 收益:{{ scope.row.syl }}U </span>
              </div>
            </div>
          </div>
        </template>
      </el-table-column>

      <!-- 时间信息合并列 -->
      <el-table-column label="时间信息" align="center">
        <template slot-scope="scope">
          <div style="text-align: center;">
            <div style="text-align: left; display: inline-block; line-height: 1.5;">
              <div>观测:{{ parseTime(scope.row.gcTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</div>
              <div>开仓:{{ parseTime(scope.row.creatTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</div>
              <div>平仓:{{ parseTime(scope.row.saleTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</div>
            </div>
          </div>
        </template>
      </el-table-column>

      <!-- 回测结果合并列 -->
      <el-table-column label="回测结果" align="center" width="160">
        <template slot-scope="scope">
          <div style="text-align: center;">
            <div style="text-align: left; display: inline-block; line-height: 1.5;">
              <div>方式:{{ scope.row.type }}</div>
              <div :style="{color: scope.row.czEnd && scope.row.czEnd.includes('成功') ? '#67c23a' : '#f56c6c'}">
                结论:{{ scope.row.czEnd }}
              </div>
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="备注信息" align="center" width="550">
        <template slot-scope="scope">
          <div style="text-align: left; line-height: 1.5;">
            <div>{{ scope.row.msg }}</div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改数据回测对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDetails, getDetails, delDetails, addDetails, updateDetails, selectTotal } from "@/api/bussiness/details"

export default {
  name: "Details",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 数据回测表格数据
      detailsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 更新时间时间范围
      daterangeGcTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        planId: null,
        instId: null,
        bar: null,
        gcTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      totalData: {} // 用来存放 selectTotal 接口返回的数据
    }
  },
  created() {
    this.setDefaultDateRange()
    this.getList()
    this.selectTotal() // 初始化时也调用统计接口
  },
  methods: {
    /** 设置默认日期范围 - 当前前一天到今日 */
    setDefaultDateRange() {
      const now = new Date()
      const yesterday = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1)

      // 格式化开始日期为 yyyy-MM-dd 08:00:00
      const formatStartDate = (date) => {
        const year = date.getFullYear()
        const month = (date.getMonth() + 1).toString().padStart(2, '0')
        const day = date.getDate().toString().padStart(2, '0')
        return `${year}-${month}-${day} 08:00:00`
      }

      // 格式化结束日期为 yyyy-MM-dd 23:59:59
      const formatEndDate = (date) => {
        const year = date.getFullYear()
        const month = (date.getMonth() + 1).toString().padStart(2, '0')
        const day = date.getDate().toString().padStart(2, '0')
        // return `${year}-${month}-${day} 23:59:59`
        return `${year}-${month}-${day} 08:00:00`
      }

      // 设置默认日期范围
      this.daterangeGcTime = [
        formatStartDate(yesterday),
        formatEndDate(now)
      ]
    },

    /** 处理日期范围变化 */
    handleDateRangeChange() {
      if (this.daterangeGcTime && this.daterangeGcTime.length === 2) {
        // 格式化开始日期为 yyyy-MM-dd 08:00:00
        const formatStartDate = (dateStr) => {
          const date = new Date(dateStr)
          const year = date.getFullYear()
          const month = (date.getMonth() + 1).toString().padStart(2, '0')
          const day = date.getDate().toString().padStart(2, '0')
          return `${year}-${month}-${day} 08:00:00`
        }

        // 格式化结束日期为 yyyy-MM-dd 23:59:59
        const formatEndDate = (dateStr) => {
          const date = new Date(dateStr)
          const year = date.getFullYear()
          const month = (date.getMonth() + 1).toString().padStart(2, '0')
          const day = date.getDate().toString().padStart(2, '0')
          return `${year}-${month}-${day} 07:59:59`
        }

        // 更新日期范围，确保时间部分正确
        this.daterangeGcTime = [
          formatStartDate(this.daterangeGcTime[0]),
          formatEndDate(this.daterangeGcTime[1])
        ]
      }
    },

    /** 查询数据回测列表 */
    getList() {
      this.loading = true
      this.queryParams.params = {}
      if (null != this.daterangeGcTime && '' != this.daterangeGcTime && this.daterangeGcTime.length === 2) {
        this.queryParams.params["beginGcTime"] = this.daterangeGcTime[0]
        this.queryParams.params["endGcTime"] = this.daterangeGcTime[1]
      }
      listDetails(this.queryParams).then(response => {
        this.detailsList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        planId: null,
        planSimple: null,
        instId: null,
        bar: null,
        gcTime: null,
        monitorYz: null,
        kpj: null,
        wtj: null,
        zyj: null,
        zsj: null,
        syl: null,
        mcj: null,
        creatTime: null,
        saleTime: null,
        czEnd: null,
        type: null,
        msg: null,
        updateTime: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
      this.selectTotal() // 搜索时调用统计接口
    },
    /** 重置按钮操作 */
    resetQuery() {
      // 重置观测时间范围
      this.setDefaultDateRange()
      this.resetForm("queryForm")
      this.handleQuery()
      // resetQuery 会调用 handleQuery，所以不需要重复调用 selectTotal
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateDetails(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addDetails(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },

    /** 格式化币种显示，去掉-USDT-SWAP */
    formatInstId(instId) {
      if (!instId) return ''
      return instId.replace('-USDT-SWAP', '')
    },
    /** 根据收益值返回颜色 */
    getSylColor(syl) {
      if (syl > 0) {
        return '#67c23a' // 绿色
      } else if (syl < 0) {
        return '#f56c6c' // 红色
      }
      return '' // 默认颜色
    },

    /** 调用selectTotal接口获取统计信息 */
    selectTotal() {
      const params = {
        ...this.queryParams,
        params: this.queryParams.params
      }
      // 使用导入的 selectTotal 方法
      selectTotal(params).then(res => {
        this.totalData = res;
      }).catch(error => {
        console.error('获取统计信息失败:', error)
        this.$modal.msgError("获取统计信息失败")
      })
    },

    /** 格式化时间显示 */
    parseTime(time, format) {
      if (!time) return ''
      // 这里使用项目中的时间格式化方法，如果项目中有全局方法可以直接使用
      // 如果没有，可以引入或实现一个简单的时间格式化
      const date = new Date(time)
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      const hour = date.getHours().toString().padStart(2, '0')
      const minute = date.getMinutes().toString().padStart(2, '0')
      const second = date.getSeconds().toString().padStart(2, '0')

      return format
        .replace('{y}', year)
        .replace('{m}', month)
        .replace('{d}', day)
        .replace('{h}', hour)
        .replace('{i}', minute)
        .replace('{s}', second)
    },

    // formatSyl(row) {
    //   const value = row.syl
    //   const plan = row.planSimple
    //   if (value > 0) {
    //     return `方案${row.planId}:${plan}<br>最终收益:<span style="color:#67C23A">赚${value.toFixed(2)}U</span>`
    //   } else if (value < 0) {
    //     return `方案${row.planId}:${plan}<br>最终收益:<span style="color:#F56C6C">亏${Math.abs(value).toFixed(2)}U</span>`
    //   }
    //   return `方案:${plan}<br>最终收益:持平`
    // }
  }
}
</script>

<style scoped>
.statistics-panel {
  margin-bottom: 10px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 2px;
}

.statistics-panel .stat-item {
  display: block;
  margin-bottom: 10px;
  font-size: 15px; /* 这会同时影响label和值 */
}
</style>
